package com.tpv.myapp.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tpv.myapp.security.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.Instant;

@Component
public class AuditingMetaObjectHandler implements MetaObjectHandler {
    private final static Logger log = LoggerFactory.getLogger(AuditingMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdDate", Instant::now, Instant.class);
        this.strictInsertFill(metaObject, "createdBy", () -> SecurityUtils.getCurrentUserLogin().orElse("admin"), String.class);
        this.strictInsertFill(metaObject, "lastModifiedDate",Instant::now, Instant.class);
        this.strictInsertFill(metaObject, "lastModifiedBy", () -> SecurityUtils.getCurrentUserLogin().orElse("admin"), String.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("lastModifiedDate", Instant.now(), metaObject);
        this.setFieldValByName("lastModifiedBy", SecurityUtils.getCurrentUserLogin().orElse("admin"), metaObject);
    }
}
